package com.moon.back.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.moon.back.constant.RedisConstant;
import com.moon.back.entity.dto.UserDto;
import com.moon.back.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 16905
 */
@Api( "用户管理")
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedissonClient redissonClient;




    // 获取当前在线人数
    @ApiOperation( "获取在线人数")
    @RequestMapping("/online")
    public SaResult online() {
        // zadd命令。有序列表处理
        RScoredSortedSet<String> sortedSet = redissonClient.getScoredSortedSet(RedisConstant.DEV_INLINE_NUM);
        //   Arrays.binarySearch()
        int count = sortedSet.count(System.currentTimeMillis(),
                Boolean.TRUE,
                Double.POSITIVE_INFINITY,
                Boolean.TRUE);

        return SaResult.data(count);
    }

    // 登录
    @ApiOperation( "登录")
    @RequestMapping("/login")
    public SaResult login(@RequestBody UserDto userDto) {
        return userService.login(userDto);
    }

    // 注册
    @ApiOperation( "注册")
    @RequestMapping("/register")
    public SaResult register(@RequestBody UserDto userDto) {
        return userService.register(userDto);
    }

    // 登出
    @RequestMapping("/logout")
    @ApiOperation( "登出")
    public SaResult logout(Integer loginId,HttpServletRequest request) {
        return userService.logout(loginId,request);
    }

    // 查看是否是登录状态
    @RequestMapping("/isLogin")
    @ApiOperation( "查看登陆状态")
    public SaResult isLogin(Integer loginId) {
        boolean login = StpUtil.isLogin(loginId);
        return SaResult.data(login);
    }


    // 查看用户详情
    @CrossOrigin
    @RequestMapping("/getUserInfo")
    @ApiOperation("查看用户详情")
    public SaResult getUserInfo(HttpServletRequest request) {
        return userService.getUserInfo(request);
    }
}

